package com.weiyuwqj.controller.item;

import com.weiyuwqj.api.model.BasDebt;
import com.weiyuwqj.api.model.BusItemInvest;
import com.weiyuwqj.api.service.*;
import com.weiyuwqj.api.common.Calculator;
import com.weiyuwqj.api.common.RepayPlan;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.model.BasItem;
import com.weiyuwqj.api.model.BasTicket;
import com.weiyuwqj.api.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyong on 2016/11/24.
 */
@Controller
public class ItemInvestController {

    @Autowired
    BasItemService itemService;
    @Autowired
    BasTicketService ticketService;
    @Autowired
    BasCouponService couponService;
    @Autowired
    BusInvestService investService;
    @Autowired
    BasDebtService debtService;

    /**
     * 实时计算收益
     */
    @ResponseBody
    @RequestMapping(value="/invest/calculator", method= RequestMethod.POST)
    public Object calculator(BigDecimal amount,Integer itemId,Integer ticketId,Integer debtId){
        int id=itemId;
        BasItem item=itemService.selectByKey(id);
        BigDecimal interest=BigDecimal.ZERO;
        if(null !=ticketId && ticketId>0){
            BasTicket ticket=ticketService.selectByKey(ticketId);
            BasItem ticketItem = new BasItem();
            BeanUtils.copyProperties(item,ticketItem);
            ticketItem.setItemRate(ticket.getRate());
            ticketItem.setItemAddRate(BigDecimal.ZERO);
            Integer cycle;
            if(ticket.getUsefulLife()<item.getItemCycle()){
                cycle = ticket.getUsefulLife();
            }else {
                cycle = item.getItemCycle();
            }
            ticketItem.setItemCycle(cycle);
            BigDecimal ticketAmount = Calculator.addRateInterest(amount, ticketItem);
            interest = interest.add(ticketAmount);
        }
        if(null ==amount){
            amount=BigDecimal.ZERO;
        }

        //判断是否是债权转让
        if(debtId != null && debtId > 0){
            //查询债权信息
            BasDebt debt = debtService.selectByKey(debtId);
            //查询原投资记录
            BusItemInvest itemInvest = null ; //investService.selectByKey(debt.getInvestId());
            //实际金额
            amount = amount.multiply(itemInvest.getInvestDealAmount()).divide(debt.getAmount(),2,BigDecimal.ROUND_DOWN);
            //实际天数
            Integer day = debt.getRestPeriods()/30;
            Integer days = debt.getRestPeriods()%30;
            if(days>0){
                day = day + 1;
            }
            item.setItemCycle(day*30);
        }

        List<RepayPlan> list= Calculator.getPlanTime(amount, item);
        for(int i=0;i<list.size();i++){
            RepayPlan plan=list.get(i);
            interest = interest.add(plan.getInterest());
        }
        interest=interest.setScale(2,BigDecimal.ROUND_HALF_DOWN);
        Map map=new HashMap();
        map.put("interest",interest+"");
        return map;
    }

    /**
     * 投资时显示红包
     * @param amount 投资金额
     * @return
     */
    @ResponseBody
    @RequestMapping("/invest/coupon")
    public Object itemCoupon(HttpServletRequest request,Double amount,Integer cycle,Integer itemId){
        Integer userId=(Integer)request.getSession().getAttribute("userId");
        //查询标的
        BasItem item = itemService.selectByKey(itemId);
        Map map=new HashMap();
        map.put("newDate",new Date());
        map.put("userId",userId);
        map.put("amount",amount);
        map.put("cycle",cycle);
        map.put("isNew",item.getItemIsnew());
        return couponService.getListByUserId(map);
    }


    /**
     * 投资时显示加息券
     * @param amount 投资金额
     * @return
     */
    @ResponseBody
    @RequestMapping("/invest/ticket")
    public Object itemTicket(HttpServletRequest request,Double amount,Integer cycle,Integer itemId){
        //查询标的
        BasItem item = itemService.selectByKey(itemId);
        Integer userId=(Integer)request.getSession().getAttribute("userId");
        Map map=new HashMap();
        map.put("newDate",new Date());
        map.put("userId",userId);
        map.put("amount",amount);
        map.put("cycle",cycle);
        map.put("isNew",item.getItemIsnew());
        return ticketService.getListByUserId(map);
    }

    /**
     * 项目的购买
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/invest/buy")
    public Object buy(HttpServletRequest request,BigDecimal amount,Integer itemId,Integer couponId,Integer ticketId,String payPassword){
        Integer userId=(Integer)request.getSession().getAttribute("userId");
        return null ;//investService.doInvest(userId,amount,itemId,couponId,1,ticketId,payPassword);
    }

    /**
     * 定向密码校验
     */
    @ResponseBody
    @RequestMapping(value = "/invest/password")
    public Object password(String password,Integer itemId){
        Integer id=itemId;
        BasItem item=itemService.selectByKey(id);
        if(StringUtils.isNull(item.getPassword())){
           throw new CrowdException("invest_password.not_exists");
        }
        if(!item.getPassword().equals(password)){
            throw new CrowdException("invest_password.password_error");
        }
        return Message.OK;
    }
}
